<style lang="scss">
.patrol-list-container {
  .el-pagination {
    padding: 16px 0;

    .btn-prev,
    .btn-next {
      margin: 0;
      margin-right: 6px;
    }
  }

  .header-container {
    padding-bottom: 20px;

    &__item {
      margin-right: 10px;
    }
  }

  .actions {
    .el-button {
      margin: 5px;
    }
  }
  .content{
    display: flex;
    margin-top: 20px;
    .sift{
      margin-right: 40px;
    }
    .search{
      width: 200px;
    }

    .name{
      margin-right: 10px
    }
  }
  .block{
    display: flex;
    justify-content: center;
  }
}
</style>

<script>
import dayjs from 'dayjs'
import CreatePatrolGroup from './components/createPatrolGroup.vue'
import PatrolGroupDetails from './components/patrolGroupDetails.vue'
import DeletePatrolGroup from './components/deletePatrolGroup.vue'
import EditPatrolGroup from './components/editPatrolGroup.vue'
import { patrolGroups } from '@/api/watchman'

export default {
  components: {
    PatrolGroupDetails,
    EditPatrolGroup,
    DeletePatrolGroup,
    CreatePatrolGroup
  },
  data() {
    return {
      patrolGroups: [],
      idToBeEdited: null,
      idToBeLookUp: null,

      loadingStatuses: {
        loading: false
      },
      visibleStatuses: {
        createPatrolGroupDialog: false,
        updatePatrolGroupDialog: false,
        patrolGroupDetails: false,

        deletePopover: false
      },
      pagination: {
        size: 10,
        current: 1,
        total: 0
      },
      name: '',
      username: ''
    }
  },
  computed: {
    patrolGroupsFormatted() {
      return this.patrolGroups.map((plan) => {
        const {
          id,
          name,
          type,
          user_count: memberCount,
          legal_holidays,
          rule,
          created_at,
          updated_at,
          user
        } = plan

        return {
          id,
          name,
          type,
          memberCount,
          ruleCount: rule.length,
          ignoreHoliday: this.ignoreHolidayStateFormatter(legal_holidays),
          createdAt: dayjs(created_at).format('YYYY-MM-DD HH:MM:ss'),
          updatedAt: dayjs(updated_at).format('YYYY-MM-DD HH:MM:ss'),
          user
        }
      })
    }
  },
  created() {
    this.initData()
  },
  methods: {
    // Events
    handlePageChange(currentPage) {
      this.pagination.current = currentPage
      this.refreshTable()
    },
    handlePageSizeChange(size) {
      this.pagination.size = size
      this.refreshTable()
    },
    handleCreateSuccess() {
      this.visibleStatuses.createPatrolGroupDialog = false
      this.$message.success('创建成功')
      this.refreshTable()
    },
    handleCreateFail() {
      this.visibleStatuses.createPatrolGroupDialog = false
      this.$message.error('创建失败')
    },
    handleUpdateSuccess() {
      this.visibleStatuses.updatePatrolGroupDialog = false
      this.$message.success('保存成功，您的修改将在次日生效')
      this.refreshTable()
    },
    handleUpdateFail() {
      this.$message.success('修改失败')
    },
    handleDelSuccess() {
      this.$message.success('删除成功')
      this.refreshTable()
    },
    handleDelFail(e) {
      this.$message.error('删除失败')
    },

    handleEdit(index, patrolPlan) {
      this.idToBeEdited = patrolPlan.id
      this.visibleStatuses.updatePatrolGroupDialog = true
    },
    handleCreate() {
      this.visibleStatuses.createPatrolGroupDialog = true
    },
    handleLookUp(index, patrolGroup) {
      this.visibleStatuses.patrolGroupDetails = true
      this.idToBeLookUp = patrolGroup.id
    },

    sleep(t) {
      return new Promise((r) => setTimeout(r, t))
    },
    ignoreHolidayStateFormatter(state) {
      console.log(state)
      const m = {
        0: '否',
        1: '是'
      }
      return m[state] ?? '未知'
    },

    async refreshTable() {
      try {
        if (this.loadingStatuses.loading) return
        this.loadingStatuses.loading = true
        await this.sleep(400)
        await this.loadData()
        this.loadingStatuses.loading = false
      } catch (e) {
        this.loadingStatuses.loading = false
      }
    },
    async getPatrolList() {
      const { current, size } = this.pagination

      const params = {
        page: current,
        paginate: size,
        name: this.name,
        username: this.username
      }

      const result = await patrolGroups(params)
      this.patrolGroups = result.data.data
      this.pagination.total = result.data.total
    },
    async loadData() {
      const result = await Promise.allSettled([this.getPatrolList()])

      const failTasks = result.filter((task) => task.status === 'rejected')
      if (failTasks.length <= 0) return

      throw failTasks[0].reason
    },
    async initData() {
      try {
        this.loadingStatuses.loading = true
        await this.sleep(400)
        await this.loadData()
        this.loadingStatuses.loading = false
      } catch (e) {
        this.loadingStatuses.loading = false
      }
    },
    onSubmit() {
      this.pagination.current = 1
      this.getPatrolList()
    }
  }
}
</script>

<template>
  <div class="app-container patrol-list-container">
    <CreatePatrolGroup
      v-model="visibleStatuses.createPatrolGroupDialog"
      @success="handleCreateSuccess"
      @fail="handleCreateFail"
    />

    <PatrolGroupDetails
      v-model="visibleStatuses.patrolGroupDetails"
      :group-id="idToBeLookUp"
    />

    <EditPatrolGroup
      v-model="visibleStatuses.updatePatrolGroupDialog"
      :group-id="idToBeEdited"
      @success="handleUpdateSuccess"
    />

    <el-card shadow="never" style="margin-bottom: 20px; border: none;">
      <el-row :gutter="40" justify="center">
        <el-col :span="24">
          <div class="header-container" style="padding-bottom: 0">

            <div class="content" style="margin-top: 0">
              <div class="sift">
                <span class="name">小组名称</span>
                <el-input
                  v-model="name"
                  class="search"
                  placeholder="请输入小组名称"
                />
              </div>
              <div class="sift">
                <span class="name">名字</span>
                <el-input
                  v-model="username"
                  class="search"
                  placeholder="请输入小组内人员名字"
                />
              </div>
              <div>
                <el-button type="primary" @click="onSubmit">查询</el-button>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <el-card shadow="never" style="border: none;">
      <div class="header-container">
        <el-button
          class="header-container__item"
          type="primary"
          icon="el-icon-plus"
          @click="handleCreate"
        >
          创建小组
        </el-button>

        <el-button
          class="header-container__item"
          icon="el-icon-refresh-right"
          @click="refreshTable"
        >
          刷新
        </el-button>
      </div>
      <el-row :gutter="40">
        <el-col :span="24">
          <el-table
            v-loading="loadingStatuses.loading"
            :data="patrolGroupsFormatted"
            style="width: 100%"
            border
          >

            <el-table-column prop="name" label="名称" width="180" />

            <el-table-column label="类型" width="180">
              <template slot-scope="scope">
                <el-popover trigger="hover" placement="top">
                  <p>标题: {{ scope.row.type.name }}</p>
                  <p>描述: {{ scope.row.type.explain }}</p>

                  <div slot="reference" class="name-wrapper">
                    {{ scope.row.type.name }}
                  </div>
                </el-popover>
              </template>
            </el-table-column>

            <el-table-column
              label="自动跳过节假日"
              width="180"
              prop="ignoreHoliday"
            >
              <template slot-scope="scope">
                <el-tag>{{ scope.row.ignoreHoliday }}</el-tag>
              </template>
            </el-table-column>

            <!-- <el-table-column prop="memberCount" label="小组成员数量" /> -->

            <el-table-column label="小组成员名字" width="180">
              <template slot-scope="scope">
                <el-tag
                  v-for="item in scope.row.user"
                  :key="item.id"
                  style="margin-left: 5px"
                >{{ item.username }}</el-tag>
              </template>
            </el-table-column>

            <el-table-column prop="ruleCount" label="规则数量" />

            <el-table-column prop="createdAt" label="创建时间" />

            <el-table-column prop="updatedAt" label="最后修改" />

            <el-table-column prop="actions" label="操作" fixed="right">
              <template slot-scope="scope">
                <div class="actions">
                  <el-button
                    circle
                    plain
                    icon="el-icon-view"
                    @click="handleLookUp(scope.$index, scope.row)"
                  />

                  <el-button
                    circle
                    plain
                    type="primary"
                    icon="el-icon-edit"
                    @click="handleEdit(scope.$index, scope.row)"
                    @success="handleUpdateSuccess"
                    @fail="handleUpdateFail"
                  />

                  <DeletePatrolGroup
                    :patrol-group-id="scope.row.id"
                    @success="handleDelSuccess"
                    @fail="handleDelFail"
                  />
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <el-row :gutter="40">
        <el-col :span="24">
          <el-pagination
            style="padding-bottom: 0;"
            class="block"
            layout="total, sizes, prev, pager, next, jumper"
            :current-page="pagination.current"
            :page-sizes="[10, 50, 100]"
            :page-size="pagination.size"
            :total="pagination.total"
            :disabled="loadingStatuses.loading"
            @size-change="handlePageSizeChange"
            @current-change="handlePageChange"
          />
        </el-col>
      </el-row>
    </el-card>

  </div>
</template>
